package com.example.wjy;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import com.example.onion.hxchat.util.PassWordHelp;
import com.example.room.entity.MyJoinTeam;
import com.example.room.entity.Team;
import com.example.superyi.myteam.R;
import com.example.superyi.myteam.databinding.ActivityMyTeamBinding;
import com.example.wjy.adapter.MyTeamAdapter;
import com.example.wjy.fragments.MyCreateTeamFragment;
import com.example.wjy.fragments.MyJoinTeamFragment;
import com.example.wjy.util.CreateId;
import com.example.wjy.viewmodels.MyCreateTeamViewModel;
import com.example.wjy.viewmodels.MyJoinTeamViewModel;
import com.example.wjy.viewmodels.MyTeamViewModel;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 显示“我的组队”的activity
 */
public class MyTeamActivity extends AppCompatActivity {

    /**
     * ViewModel of MyCreateTeamFragment with ViewModelStoreOwner this activity.
     */
    MyCreateTeamViewModel myCreateTeamViewModel;

    /**
     * ViewModel of this activity.
     */
    MyTeamViewModel myTeamViewModel;

    /**
     * DataBinding of this activity and activity_my_team.
     */
    public ActivityMyTeamBinding binding;

    /**
     * The adapter of ViewPager2.
     */
    MyTeamAdapter myTeamAdapter;

    MyJoinTeamViewModel myJoinTeamViewModel;

    /**
     * An instance of MyCreateTeamFragment.
     */
    MyCreateTeamFragment myCreateTeamFragment = new MyCreateTeamFragment();

    /**
     * An instance of MyCreateTeamFragment.
     */
    MyJoinTeamFragment myJoinTeamFragment = new MyJoinTeamFragment();

    String teamId;
    List<MyJoinTeam> teams;
    String userId;
    String url = "http://49.232.60.155:8080/AppServer_war/TeamServlet";

    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMyTeamBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        myJoinTeamViewModel = new ViewModelProvider(this).get(MyJoinTeamViewModel.class);

        userId = PassWordHelp.readPassword(this)[0];
        myCreateTeamViewModel = new ViewModelProvider(this).get(MyCreateTeamViewModel.class);
        myTeamViewModel = new ViewModelProvider(this).get(MyTeamViewModel.class);

        Intent intent = getIntent();

        Log.d("debug","执行到MyTeamActivity");
        if("0".equals(intent.getStringExtra("tag"))) {
            String teamName = intent.getStringExtra("name");
            String teamKind = intent.getStringExtra("kind");
            teamId = CreateId.createRandomId();
            String teamIntro = intent.getStringExtra("introduction");
            String teamNumOfAll = String.valueOf(intent.getIntExtra("numOfAll",1));
//            Team team = new Team(teamName,teamKind,Integer.parseInt(teamNumOfAll),1,teamIntro,"null");
//            team.setId(teamId);
            Team team = new Team(teamId,1,teamKind,teamName,"null",teamIntro,
                    Integer.parseInt(teamNumOfAll),1);
            team.setTeamId(teamId);
            //调整为在服务器中同时创建小队，成功了，可以同时修改
            new Thread(() -> {
                OkHttpClient client = new OkHttpClient();
                //传递的参数是以键值对传输的
                String userId = PassWordHelp.readPassword(this)[0];
                String userState = "2";
                RequestBody requestBody = new FormBody.Builder()
                        .add("teamId",teamId)
                        .add("teamName",teamName)
                        .add("teamKind",teamKind)
                        .add("teamIntro",teamIntro)
                        .add("teamNumOfAll",teamNumOfAll)
                        .add("userId",userId)
                        .add("userState",userState)
                        .add("flag","1")
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();
                Call call =  client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                    }
                });

            }).start();


            myCreateTeamViewModel.insertTeam(team);
        }



        //定义两个碎片，分别承载“我创建的组队”和“我加入的组队”
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(myCreateTeamFragment);
        fragments.add(myJoinTeamFragment);

        //View Pager2的适配器
        myTeamAdapter = new MyTeamAdapter(this, fragments);

        binding.viewPager2.setAdapter(myTeamAdapter);

        //ViewPager2滑动事件监听器
        binding.viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                switch (position) {
                    case 0:
                        Log.d("tag1", "fragment1");
                        break;
                        //滑动到我加入的组队，每次进入都从服务器请求数据到本地
                    case 1:
                        new Thread(() -> {
                            OkHttpClient client = new OkHttpClient();
                            //传递的参数是以键值对传输的

                            RequestBody requestBody = new FormBody.Builder()
                                    .add("userId",userId)
                                    .add("flag","5")
                                    .add("userState","1")
                                    .build();
                            Request request = new Request.Builder()
                                    .url(url)
                                    .post(requestBody)
                                    .build();
                            Call call =  client.newCall(request);
                            call.enqueue(new Callback() {
                                @Override
                                public void onFailure(@NotNull Call call, @NotNull IOException e) {

                                }

                                @Override
                                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                    String json = response.body().string();
                                    Gson gson = new Gson();
                                    teams = gson.fromJson(json,new TypeToken<List<MyJoinTeam>>(){}.getType());
                                    myJoinTeamViewModel.deleteAllTeam();
                                    for(int i = 0;i < teams.size();++i)
                                        myJoinTeamViewModel.insertTeam(teams.get(i));
                                }
                            });

                        }).start();






                        break;
                    default:
                        break;
                }
            }
        });

        //设置TabLayout
        new TabLayoutMediator(binding.tabLayout, binding.viewPager2, (tab, position) -> {
            TextView tabView = new TextView(MyTeamActivity.this);
            tabView.setText(myTeamViewModel.tabList.get(position));
            tabView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tab.setCustomView(tabView);
        }).attach();
    }

    
}